package spring.rabbitstomp.message.config;

import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

/**
 * rabbitmq配置
 * @author weikun
 */
@Configuration
@ConditionalOnProperty(
	name = "message.type.rabbitmq",
	havingValue = "true"
)
public class RabbitMqConfiguration {

	/**
	 * web端连接工厂，如有其他连接域方便扩展
	 * @param host 地址
	 * @param port 端口
	 * @param username 账号
	 * @param password 密码
	 * @param virtualHost mq库
	 * @return web工厂实例
	 */
	@Bean(name="webConnectionFactory")
	@Primary
	@ConditionalOnProperty(
		name = "message.type.rabbitmq",
		havingValue = "true"
	)
	public ConnectionFactory webConnectionFactory(
			@Value("${spring.rabbitmq.host}") String host,
			@Value("${spring.rabbitmq.port}") int port,
			@Value("${spring.rabbitmq.web.username}") String username,
			@Value("${spring.rabbitmq.web.password}") String password,
			@Value("${spring.rabbitmq.web.virtual-host}") String virtualHost){
		CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
		connectionFactory.setHost(host);
		connectionFactory.setPort(port);
		connectionFactory.setUsername(username);
		connectionFactory.setPassword(password);
		connectionFactory.setVirtualHost(virtualHost);

		return connectionFactory;
	}

	@Bean(name="webRabbitTemplate")
	@Primary
	@ConditionalOnProperty(
		name = "message.type.rabbitmq",
		havingValue = "true"
	)
	public RabbitTemplate webRabbitTemplate(@Qualifier("webConnectionFactory") ConnectionFactory connectionFactory){
		RabbitTemplate webRabbitTemplate = new RabbitTemplate(connectionFactory);
		//使用外部事物
		//ydtRabbitTemplate.setChannelTransacted(true);
		return webRabbitTemplate;
	}


}
